/*
 * Student Name: Philippe Gambling
 * Course: CSCI 5733
 * Assignment: Homework 1
 * Created: Jun 20, 2009
 * Modified: Jun 20, 2009
 * 
 * Class Name: Cache
 * Description: A very simple file cache.
 */

package csci5733.hw1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Date;

/**
 *
 * @author Philippe Gambling
 */
public class Cache {
    private static int expire = 3*60000; // Length of time to cache data (3 minutes)

    private static void writeFile(String fname, String content) {
		FileOutputStream fout;

		try
		{
		    fout = new FileOutputStream (fname);
		    new PrintStream(fout).println (content);
		    fout.close();
		}
		catch (IOException ex)
		{
			System.out.println ("Unable to write to "+fname);
			ex.printStackTrace();
		}

    }

    private static String readFile(String fname) {
        
        File file = new File(fname);
        Date now = new Date();
        Date fileExpire = new Date(file.lastModified()+Cache.expire);
        
        // Read file if it exists and hasn't expired
        if((file.exists()) && (fileExpire.after(now)) ) {
            BufferedReader fin;
            String content = "", line;

            try
            {
                fin = new BufferedReader(new FileReader(file));
                while((line = fin.readLine()) != null) {
                    content += line+'\n';
                }
                fin.close();
            }
            catch (IOException ex)
            {
                System.out.println ("Unable to read from "+fname);
                ex.printStackTrace();
            }

            return content;
        }

        return null;
    }

    private static synchronized String accessCache(String name, String content, String operation) {
        String fname = name+".xml";
        if(operation.equals("read")) {
            return Cache.readFile(fname);
        } else {
            Cache.writeFile(fname,content);
        }
        return new String();
    }

    public static String getData(String name) {
        String content = new String();
        return Cache.accessCache(name, content, "read");
    }

    public static void storeData(String name, String content) {
        Cache.accessCache(name, content, "write");
    }

}
